/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.task.evaluation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.cmu.lti.sepia.data.db.IRJudgmentResultDAO;
import edu.cmu.lti.sepia.data.db.IRJudgmentUnitDAO;
import edu.cmu.lti.sepia.data.db.SQL;
import edu.cmu.lti.sepia.infra.eval.model.IRJudgmentResult;
import edu.cmu.lti.sepia.infra.eval.model.IRJudgmentUnit;

public class IR4QAQrelsImport {

  private static Pattern pQrels = Pattern.compile("(ACLIA2-[^\\s]*)\\s([^\\s]*)\\s([^\\s]*)\\s?(.*)");
  
  private static int counter = 1;
  
  public static void loadQrels(SQL sql, String taskNameShort, InputStream is) 
  throws SQLException, IOException {
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while ( (line=br.readLine())!=null ) {
      Matcher m = pQrels.matcher(line);
      if (m.find()) {
        IRJudgmentUnit unit = IRJudgmentUnitDAO.findJudgmentUnitByTopicAndDocument(sql, taskNameShort, m.group(1), m.group(2));
        IRJudgmentResult result = new IRJudgmentResult(unit, 99, m.group(3), m.group(4), 0);
        try {
          IRJudgmentResultDAO.updateResult(sql, taskNameShort, result);
        } catch (NullPointerException npe) {
          System.out.println("bad >"+m.group(1)+"<>"+m.group(2)+"<");
        }
        System.out.println(counter++);
      }
    }
    System.out.println( "Finished loading qrels for "+taskNameShort );
  }
  
  public static void main(String[] args) throws Exception {
    String dir = "C:\\Users\\hideki\\Desktop\\aclia\\qrels import\\ct ir4qa";
    SQL sql = new SQL();

    loadQrels( sql, "ct_formal", new FileInputStream(new File(dir+"\\pd100-50_judgments_utf8.txt")) );
//    loadQrels( sql, "ct_formal", new FileInputStream(new File(dir+"\\ACLIA2_IR4QA_pd50_judgments_part1_utf8.txt")) );
//    loadQrels( sql, "ct_formal", new FileInputStream(new File(dir+"\\ACLIA2_IR4QA_pd50_judgments_part2_utf8.txt")) );

    sql.close();
  }
}
